package PC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zjq
 * @date 2020/3/27 10:35
 */
public class C {
    public static void main(String[] args) {
        B a = new B();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.printC();
            }
        }, "C").start();
    }
}

class B {
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    private int num = 1;//num=1 A;num = 2 B;num =3 C

    public void printA() {
        lock.lock();
        try {
            //业务
            while (num != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=======A");
            //唤醒指定的线程
            num = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void printB() {
        lock.lock();
        try {
            //业务，判断-》执行-》通知
            while (num != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=========B");
            num = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            //业务
            while (num != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "========C");
            num = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
